window.onload = function () {
    var containter = document.querySelector("#container");
    var canvas = document.createElement("canvas");
    canvas.height = containter.clientHeight;
    canvas.width = containter.clientWidth;
    containter.appendChild(canvas);
    var gl = canvas.getContext("webgl");
    gl.clearColor(0.0, 0.0, 0.0, 1.0);
    gl.clear(gl.COLOR_BUFFER_BIT);
    var VERTEX_SHADER_SOURCE =
        "attribute vec4 a_Position;\n" +
        "void main(){" +
        "gl_Position = a_Position;" +
        "gl_PointSize = 10.0;" +
        "}";

    var FRAGMENT_SHADER_SOURCE =
        "precision mediump float;\n" +
        "uniform vec4 u_FragColor;" +
        "void main(){" +
        "gl_FragColor = u_FragColor;" +
        "}";
    var vertex_shader_object = gl.createShader(gl.VERTEX_SHADER);
    var fragment_shader_object = gl.createShader(gl.FRAGMENT_SHADER);

    gl.shaderSource(vertex_shader_object, VERTEX_SHADER_SOURCE);
    gl.shaderSource(fragment_shader_object, FRAGMENT_SHADER_SOURCE);

    gl.compileShader(vertex_shader_object);
    gl.compileShader(fragment_shader_object);

    var program = gl.createProgram();

    gl.attachShader(program, vertex_shader_object);
    gl.attachShader(program, fragment_shader_object);

    gl.linkProgram(program);
    gl.useProgram(program);

    var pointsCollection = []
    canvas.onclick = function (e) {
        clientX = e.clientX;
        clientY = e.clientY;
        var x = (clientX - canvas.width / 2) / (canvas.width / 2);
        var y = (canvas.height / 2 - clientY) / (canvas.height / 2);
        pointsCollection.push(x, y);

        var u_FragColor = gl.getUniformLocation(program, "u_FragColor");
        gl.uniform4f(u_FragColor,Math.random(),Math.random(),Math.random(),1.0);

        // 1. 创建float32数组
        var vertices = new Float32Array(pointsCollection);
        // 2. 创建缓冲区对象
        var vertexBuffer = gl.createBuffer();
        // 3. 绑定缓冲区
        gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
        // 4. 缓冲区添加数据
        gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.DYNAMIC_DRAW);
        // 5. 关联属性
        var a_Position = gl.getAttribLocation(program, "a_Position");
        // 6. 传入属性
        gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0);
        // 7. 使用属性
        gl.enableVertexAttribArray(a_Position);
        // 8. 清除画布 
        gl.clearColor(.0, .0, .0, 1.0);
        gl.clear(gl.COLOR_BUFFER_BIT);
        gl.drawArrays(gl.POINTS, 0, pointsCollection.length / 2);
    };
}